<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 吃草的鱼 <783188184@qq.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Home\Controller;
use Think\Controller;
use Shop\Api\CategoryApi;
use Shop\Api\ProductApi;
use Shop\Api\ProductSkuApi;
use Shop\Api\ProductImageApi;
use Weixin\Api\WxuserApi;
use Admin\Api\UserPictureApi;
use Shop\Api\AddressApi;
use Shop\Api\OrdersApi;
use Shop\Api\OrdersItemApi;
use Shop\Api\OrdersContactInfoApi;
use Shop\Api\ProductGroupApi;
use Home\Controller\GroupController;
class UserController extends HomeController {
    /*
     * 发布商品
     * */
    public function add_good(){
        if(IS_POST){
            //存储商品信息
            $model = M();
            $model -> startTrans();
            $flag = false;
            $cate_list= explode(',',I('cate_id'));
            $all = count($cate_list);
            for($i = $all-1;$i > 0;$i--){
                if($cate_list[$i] != 0){
                    $all = $cate_list[$i];
                    break;
                }
            }

            $entity = array(
                'uid' => $this->userinfo['uid'],
                'name' => I('name'),//商品名称
                'cate_id' => $all,//商品所属栏目ID
                'createtime' => time(),//创建时间
                'updatetime' => time(),//更新时间
                'onshelf' => '0',//是否上架
                'status' => -2,//商品状态
                'synopsis' => I('synopsis'),//商品描述
                'dt_origin_country' => I('dt_origin_country'),//商品来源
                'postage' => I('postage')
            );

            $productapires = apiCall(ProductApi::ZADD, array($entity));


            //根据是否为团购商品选择商品价格信息加入
            if($all==23||$all==26){
                //当为团购商品时，存储商品的价格与原价，库存，活动时间，
                if(!$productapires['status']){
                    $flag = true;
                }
                $group= array(
                    'ori_price' => I('ori_price'),
                    'price' => I('price'),
                    'group_sum' => I('group_sum'),
                    'start_time' => I('start_time'),
                    'end_time'=>I('end_time'),
                    'quantity' => I('quantity'),
                    'p_id' => $productapires['info']
                );
                $productgroup = apiCall(ProductGroupApi::ADD, array($group));
                if(!$productgroup['status']) {
                    $flag = true;
                }
            }else{
                //当不为团购商品时，存储商品的价格与原价，库存
                if(!$productapires['status']){
                    $flag = true;
                }
                $sku = array(
                    'ori_price' => I('ori_price'),
                    'price' => I('price'),
                    'quantity' => I('quantity'),
                    'product_id' => $productapires['info']
                );
                $productsku = apiCall(ProductSkuApi::ADD, array($sku));
                if(!$productsku['status']){
                    $flag = true;
                }}

            //存储商品的相应图片
            foreach(I('img_list') as $k => $vo){
                $img['pid'] = $productapires['info'];
                $img['img_id'] = $vo;
                if($k == 0){
                    $img['type'] = 6015;//主显示图
                }
                $img['create_time'] = date('U');
                $imgres = apiCall(ProductImageApi::ADD, array($img));
            }
            if(!$imgres['status']){
                $flag = true;
            }



            if($flag){
                $model->rollback();
                $this->error('添加失败',U('User/add_good'));
            }else {
                $model->commit();
                $this->success('添加成功',U('index/index'));
            }
        }else{
            //数组分类树的生成
            header('content-type:text/html;charset=utf-8');
            $res = apiCall(CategoryApi::QUERY,array('','','','','id,name,parent'));
            $res=$res['info']['list'];
            foreach($res as $k=>$v){
                if($v['id']==4||$v['id']==23||$v['id']==26){
                    unset($res[$k]);
                }
            }
            $feilei = create_tree($res);
            $json = json_encode($feilei);
            $this->assign('feilei',$json);
            $this->display();
        }
    }

    /*
     * 实验多图上传
     * */
    public function imglist(){
        $this->display();
    }

    /*
     * 购买商品
     * */
    public function buy_good(){

        $wxusermap['uid'] = I('uid') ? I('uid') : session('uid');

        //判断是否有可供选择的地址没有就需要新建
        $hasaddrres = apiCall(AddressApi::COUNT , array($wxusermap));
        if($hasaddrres['status']){
            $this->assign('addrecount',$hasaddrres['info']);
        }
        //判断是否进行地址选择如果选择了就用选择的
        if(!empty(I('addressid'))){
            $addressmap['id'] = I('addressid');
            session('addressid',$addressmap['id']);//为的是在生成订单时获得相应的地址信息的方便
            $selectres = apiCall(AddressApi::GET_INFO , array($addressmap));
            if($selectres['status']){
                $this->assign($selectres['info']);
            }
        }else{
            //如果没有则将调用默认地址
            $addressdefaultmap['itboye_address.uid'] = $wxusermap['uid'];
            $res = apiCall(WxuserApi::FIND_DEFAULT_ADDRESS , array($addressdefaultmap));//联合查询查出默认地址
            if($res['status']){
                session('addressid',$res['info']['id']);
                $this->assign($res['info']);
            }
        }
        //调出商品信息
        $product['id'] = I('id') ? I('id') : session('id');//商品id
        session('id',$product['id']);//存入商品ID
        session('uid',$wxusermap['uid']);//存入购买者用户

        $res = apiCall(ProductApi::ALLQUERY, array($product,'','','','id,uid,name,synopsis,postage,img_id,type'));
        foreach($res['info']['list'] as $vo){
            $imgcondition['id'] = $vo['img_id'];
            $img = apiCall(UserPictureApi::GET_INFO, array($imgcondition));
            $skucondition['product_id'] = $vo['id'];
            $productsku = apiCall(ProductSkuApi::GET_INFO, array($skucondition));
            $productimglist[$vo['id']]['id'] = $vo['id'];//商品id
            $productimglist[$vo['id']]['uid'] = $vo['uid'];//发布商品的用户id
            $productimglist[$vo['id']]['name'] = $vo['name'];
            $productimglist[$vo['id']]['synopsis'] = $vo['synopsis'];//介绍
            $productimglist[$vo['id']]['postage'] = $vo['postage'];//邮费
            if(count($productimglist[$vo['id']]['imglist']) < 1){//先调用第一张图片作为主图到时候在调整
                $productimglist[$vo['id']]['imglist'][] = $img['info'];//需要判断图片是不是大于3张了
            }
            $productimglist[$vo['id']]['price'] = $productsku['info']['price'];
            $productimglist[$vo['id']]['ori_price'] = $productsku['info']['ori_price'];
            $productimglist[$vo['id']]['number'] = $productsku['info']['quantity'];//商品库存
            //将发布者的信息查出放入数组
            $Wusermap['id'] = $vo['uid'];
            $productwx = apiCall(WxuserApi::GET_INFO, array($Wusermap));
            $productimglist[$vo['id']]['nickname'] = $productwx['info']['nickname'];
            $productimglist[$vo['id']]['avatar'] = $productwx['info']['avatar'];
        }
        $this->assign($productimglist[$product['id']]);
        $this->display();
    }

    /*
     * 订单信息的生成
     * */
    public function produce_order(){
        if(empty(I('addressid'))&&empty(session('addressid'))) $this->error("没有填写地址");
        if(IS_POST){
            $model = M();
            $model -> startTrans();//开启事务
            $flag = false;

            session('addressid', I('addressid') ? I('addressid') : session('addressid'));//存入送货地址
            $productmap['id'] = session('id');
            $productskumap['product_id'] = $productmap['id'];
            $buy_number = I('number','1');//购买商品的数量
            $productinfo = apiCall(ProductApi::GET_INFO,array($productmap));//运用session将相应的信息查询出来
            $productskuinfo = apiCall(ProductSkuApi::GET_INFO, array($productskumap));//运用session将相应的价格信息查询出来

            //下面要做一个判断防止返回时有重复提交订单  导致有多个订单存在
            if($productinfo['info']['status'] == 1 && $productskuinfo['info']['quantity'] >= $buy_number) {
                //生成order表的数据存入
                $entity['uid'] = session('uid');//用户的ID
                $entity['price'] = $productskuinfo['info']['price'];
                $entity['order_code'] = getOrderid($entity['uid']);//获得订单编号
                $entity['ori_price'] = $productskuinfo['info']['ori_price'];
                $entity['post_price'] = $productinfo['info']['postage'];//邮费
                $entity['uid'] = session('uid');//用户id
                $entity['status'] = 1;
                $entity['pay_status'] = 0;
                $entity['order_status'] = 2;
                $entity['cs_status'] = 0;
                $entity['createtime'] = time();
                $entity['updatetime'] = time();

                $orderinfo = apiCall(OrdersApi::ADD, array($entity));
                if (!$orderinfo['status']) {
                    $flag = true;
                }

                //找到一张图片作为主图放入到item当中作为商品的头像
                $imgidmap['pid'] = $productmap['id'];
                $imgidinfo = apiCall(ProductImageApi::GET_INFO, array($imgidmap));
                if (!$imgidinfo['status']) {
                    $flag = true;
                }
                $imgmap['id'] = $imgidinfo['info']['img_id'];
                $imginfo = apiCall(UserPictureApi::GET_INFO, array($imgmap));
                if (!$imginfo['status']) {
                    $flag = true;
                }
                //订单编号的生成并item和order表相关联
                $item['img'] = $imginfo['info']['path'];
                $item['name'] = $productinfo['info']['name'];
                $item['price'] = $productskuinfo['info']['price'];
                $item['ori_price'] = $productskuinfo['info']['ori_price'];
                $item['post_price'] = $productinfo['info']['postage'];
                $item['count'] = $buy_number;
                $item['order_code'] = $entity['order_code'];//获得订单编号
                $item['createtime'] = time();
                $item['p_id'] = $productmap['id'];
                $item['dt_origin_country'] = $productinfo['info']['dt_origin_country'];
                $orderiteminfo = apiCall(OrdersItemApi::ADD, array($item));
                if (!$orderiteminfo['status']) {
                    $flag = true;
                }
                //生成送货地址存入与货物相关联
                $addressmap['id'] = session('addressid');//获得送货地址ID
                $addressinfo = apiCall(AddressApi::GET_INFO, array($addressmap));
                $contactinfo['contactname'] = $addressinfo['info']['contactname'];
                $contactinfo['uid'] = $entity['uid'];
                $contactinfo['province'] = $addressinfo['info']['province'];
                $contactinfo['detailinfo'] = $addressinfo['info']['detailinfo'];
                $contactinfo['area'] = $addressinfo['info']['area'];
                $contactinfo['mobile'] = $addressinfo['info']['mobile'];
                $contactinfo['order_code'] = $item['order_code'];
                $contactinfo['city'] = $addressinfo['info']['city'];
                $contactres = apiCall(OrdersContactInfoApi::ADD, array($contactinfo));

                if (!$contactres['status']) {
                    $flag = true;
                }
                //减少操作
                $productsku['quantity'] = $productskuinfo['info']['quantity']-$buy_number;
                $productskures = apiCall(ProductSkuApi::SAVE,array($productskumap,$productsku));
                if(!$productskures['status']){
                    $flag = true;
                }
                if($productsku['quantity'] <= 0){
                    //如果库存数量等于0 product表中的status设置为0
                    $addstatus['status'] = 0;
                    $setproductres = apiCall(ProductApi::SAVE, array($productmap, $addstatus));//运用session将相应的信息查询出来
                    if (!$setproductres['status']) {
                        $flag = true;
                    }
                }

                if ($flag) {
                    $model->rollback();
                    $this->error('订单发送失败');
                } else {
                    $model->commit();
                    $this->success('订单生成成功', 'http://muyin.8raw.com/index.php/Home/Pay/jsapi/?' . 'order_code=' . $item['order_code']);
                }
            }else{
                $this->error('库存不够 您可以减少数量或者过段时间再来',U('index/index'));
            }

        }else{
            $this->error('大兄弟你来错地方了');
        }

        
    }

    /*
     *选择地址
     * */
    public function select_address($type=0){
        $map = array('openid' => $this -> openid, 'wxaccount_id' => $this -> wxaccount['id']);//wxaccount_id表示所属的微信公众账号
        $user = apiCall(WxuserApi::GET_INFO , array($map));
        $this->assign('d_addr',$user['info']['default_address']);
        $map = array('uid'=>$user['info']['id']);
        $result = apiCall(AddressApi::QUERY_NO_PAGING , array($map));
        $this->assign("addr",$result['info']);
        if($type == 1) {$this->display('Group/select_address');
        }else{
        $this->display();
        }
    }

    /*
     * 支付
     * */
    public function pay_money(){
        $this->display();
    }


}